package server.feedbacks;

import java.io.IOException;
import java.sql.Date;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import json.JSONObjectWrapper;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import server.database.AbstractTable;
import server.database.DatabaseService;
import server.database.query.IQueryResult;
import server.servlet.AbstractServlet;

public class FeedbacksReportServlet extends AbstractServlet
{
	private static final long serialVersionUID = 5808563511908767476L;

	public static final String PATH = API + "/feedbacks_report";

	public static final String FEEDBACKS_REPORT = "feedbacks_report";
	public static final Object DELAYED_FEEDBACKS = "delayed_feedbacks";

	@Override
	protected void doGetSpecific(HttpServletRequest request, HttpServletResponse response, JSONObject output) throws ServletException, IOException
	{
		IQueryResult queryResult = null;

		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, -3);
		Date queryDate = new Date(calendar.getTimeInMillis());

		String sWhereString = " WHERE " + FeedbacksTable.SUBMIT_DATE.getName() + " <= " + AbstractTable.parseDateForQuery(queryDate)
				+ AbstractTable.AND + FeedbacksTable.STATUS.getName() + " != " + FeedbackServlet.CLOSED;

		queryResult = getTable().getAllEntities(sWhereString);

		if (queryResult.getResult() == IQueryResult.SUCESS)
		{
			output.put(RESULT, true);

			JSONObject feedbacks_report = new JSONObject();

			JSONArray delayed_feedbacks = new JSONArray();
			buildEntityValues(queryResult.getResultValues(), delayed_feedbacks, getTable());
			feedbacks_report.put(DELAYED_FEEDBACKS, delayed_feedbacks);

			output.put(FEEDBACKS_REPORT, feedbacks_report);

		}
		else if (queryResult.getResult() != IQueryResult.NO_RESULTS)
		{
			setFail(output, UNEXPECTED_ERROR, UNEXPECTED_ERROR);
		}

	}

	@Override
	protected void doPostSpecific(JSONObjectWrapper request, JSONObject output) throws ServletException, IOException
	{
	}

	@Override
	protected FeedbacksTable getTable()
	{
		return (FeedbacksTable) DatabaseService.getInstance().getTable(FeedbacksTable.TABLE_NAME);
	}

}
